package com.ptb.uranus.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.ptb.uranus.sms.utils.JedisUtil;

public class JuheSmsSend {
	private static Logger logger = Logger.getLogger(JuheSmsSend.class);
	static ResourceBundle bundle = PropertyResourceBundle.getBundle("ptb");
	public static void main(String[] args) {
		while(true){
			 String key = "ptb::sms";
			 byte[] ph = null;
			 try {
				ph=JedisUtil.rpop(key.getBytes());
			 } catch (Exception e) {
				 logger.error("[1000] redis is error", e);
			 }
			 if (ph == null) {
	             try {
	                 Thread.sleep(2000);
                     logger.info("no send sms !");
	             } catch (InterruptedException e) {
	             }
	             continue;
		     }
			 String s = null;
			 try {
                s = new String(ph, "utf-8");
			 } catch (Exception e1) {
                logger.error("Redis To obtain message for null!"+e1);
			 }
			 JSONObject json = new JSONObject(s);
             String phone = json.getString("phone");
             String message = json.getString("message");
             String param = "mobile="+phone+"&tpl_id="+bundle.getString("sms.juhe.validation")+"&tpl_value=#code#="+message+"&dtype=&key="+bundle.getString("sms.juhe.AppKey")+"";
             sendPost(bundle.getString("sms.juhe.sendurl"), param,phone);
		}
	}
	
	/**
	 * post短信验证
	 * @param url
	 * @param param
	 * @return
	 */
	public static String sendPost(String url, String param,String phone) {
		  PrintWriter out = null;
	      BufferedReader in = null;
	      String result = "";
	      try {
			URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            logger.info(result+"phone:"+phone);
		} catch (Exception e) {
			logger.error("Abnormal request!"+param, e);
		}finally {
		    try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
		}
		return result;
	}

}
